<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/* 
	发送短信
*/
class Sendsms extends MY_Controller{
	
	public function __construct(){
		parent::__construct();
		$this->load->library('Aliyun/smslib');
	}
	
	/* public function test(){
		// $code = $this->make_code();
		// $send = $this->smslib->send_code('13294212321', $code);
		// $send = $this->smslib->send_notice('13294212321', [
			// 'parents_name' => '陈进',
			// 'student_name' => '陈七月',
			// 'campus' => '郧阳校区'
		// ]);
		// $phones = ['13294212321', '18696050029'];
		// $params = [
			// ['parent' => '曾经', 'student' => '七月'],
			// ['parent' => '蒙哥', 'student' => '小蒙']
		// ];
		// $send = $this->smslib->batch_send_notice($phones, $params, 'signup_passed');
		// $send = $this->smslib->send_notice('13294212321', [
			// 'parent' => '曾经',
			// 'student' => '七月'
		// ], 'signup_passed');
		// var_dump($send);
	} */
	
	public function code(){
		$posts = $this->input->post();
		$this->load->library('form_validation');
		$this->form_validation->set_rules('phone', '手机号码', 'required|valid_phone');
		$this->form_validation->set_rules('type', '类型', 'required');
		if($this->form_validation->run() == false){
			foreach($this->form_validation->error_array() as $filed => $error){
				$this->output_json([
					'retcode' => -1,
					'message' => $error
				]);
			}
		}
		
		$phone = $posts['phone'];
		$type = $posts['type'];
		$this->check_type();
		
		// 验证用户
		if('reg' == $type){
			$this->load->model('user_model');
			$row = $this->user_model->get_row([
				'where' => [
					'phone' => $phone
				]
			]);
			if($row){
				$this->output_json('该手机已注册');
			}
		}
		
		$tmpkey = 'smscode_'.$type.'_'.$phone;
		$this->load->library('myredis');
		if($this->myredis->get($tmpkey)){
			$this->output_json('请查看短信，稍后再获取');
		}
		$code = $this->make_code();
		$send = $this->smslib->send_code($phone, $code);
		if($send === true){
			$this->myredis->setex($tmpkey, 5*60, $code);
			$this->output_json('短信已发送', 0);
		}
		$this->output_json('短信发送失败');
	}
	
	// 判断短信类型
	private function check_type(){
		$types = [
			'reg' // 注册
		];
		if(!in_array($this->input->post('type'), $types)){
			$this->output_json('类型不正确');
		}
	}
	
	// 随机验证码
	private function make_code($len = 6){
		$chars = '0123456789';
		$charlen = strlen($chars);
		$return = '';
		for($x = 0; $x < $len; $x++){
			$return .= $chars[mt_rand(0, $charlen - 1)];
		}
		return $return;
	}
	
}